package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.ResultCode;
import com.example.entity.Volunteer;
import com.example.exception.BusinessException;
import com.example.mapper.VolunteerMapper;
import com.example.service.VolunteerService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Arrays;

@Service
public class VolunteerServiceImpl extends ServiceImpl<VolunteerMapper, Volunteer> implements VolunteerService {

    @Override
    public Page<Volunteer> getVolunteerList(Integer pageNum, Integer pageSize, String keyword, Integer status) {
        Page<Volunteer> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<Volunteer> wrapper = new LambdaQueryWrapper<>();
        
        // 关键词搜索
        if (StringUtils.hasText(keyword)) {
            wrapper.like(Volunteer::getName, keyword)
                    .or()
                    .like(Volunteer::getPhone, keyword)
                    .or()
                    .like(Volunteer::getVolunteerNumber, keyword);
        }
        
        // 状态筛选
        if (status != null) {
            wrapper.eq(Volunteer::getStatus, status);
        }
        
        wrapper.orderByDesc(Volunteer::getCreateTime);
        return page(page, wrapper);
    }

    @Override
    @Transactional
    public boolean addVolunteer(Volunteer volunteer) {
        // 检查身份证号是否已存在
        LambdaQueryWrapper<Volunteer> idCardWrapper = new LambdaQueryWrapper<>();
        idCardWrapper.eq(Volunteer::getIdCard, volunteer.getIdCard());
        if (baseMapper.selectCount(idCardWrapper) > 0) {
            throw new BusinessException(ResultCode.ID_CARD_ALREADY_EXISTS);
        }

        // 检查手机号是否已存在
        LambdaQueryWrapper<Volunteer> phoneWrapper = new LambdaQueryWrapper<>();
        phoneWrapper.eq(Volunteer::getPhone, volunteer.getPhone());
        if (baseMapper.selectCount(phoneWrapper) > 0) {
            throw new BusinessException(ResultCode.PHONE_ALREADY_EXISTS);
        }

        // 生成志愿者编号
        volunteer.setVolunteerNumber(generateVolunteerNumber());
        // 设置初始状态为待审核
        volunteer.setStatus(0);
        // 设置初始服务时长为0
        volunteer.setServiceHours(0);
        
        return save(volunteer);
    }

    @Override
    @Transactional
    public boolean updateVolunteer(Volunteer volunteer) {
        // 检查志愿者是否存在
        Volunteer existingVolunteer = getById(volunteer.getId());
        if (existingVolunteer == null) {
            throw new BusinessException(ResultCode.VOLUNTEER_NOT_FOUND);
        }

        // 如果修改了身份证号，检查新的身份证号是否已存在
        if (!existingVolunteer.getIdCard().equals(volunteer.getIdCard())) {
            LambdaQueryWrapper<Volunteer> idCardWrapper = new LambdaQueryWrapper<>();
            idCardWrapper.eq(Volunteer::getIdCard, volunteer.getIdCard());
            if (baseMapper.selectCount(idCardWrapper) > 0) {
                throw new BusinessException(ResultCode.ID_CARD_ALREADY_EXISTS);
            }
        }

        // 如果修改了手机号，检查新的手机号是否已存在
        if (!existingVolunteer.getPhone().equals(volunteer.getPhone())) {
            LambdaQueryWrapper<Volunteer> phoneWrapper = new LambdaQueryWrapper<>();
            phoneWrapper.eq(Volunteer::getPhone, volunteer.getPhone());
            if (baseMapper.selectCount(phoneWrapper) > 0) {
                throw new BusinessException(ResultCode.PHONE_ALREADY_EXISTS);
            }
        }

        return updateById(volunteer);
    }

    @Override
    @Transactional
    public boolean deleteVolunteer(Long id) {
        // 检查志愿者是否存在
        if (getById(id) == null) {
            throw new BusinessException(ResultCode.VOLUNTEER_NOT_FOUND);
        }
        return removeById(id);
    }

    @Override
    @Transactional
    public boolean batchDeleteVolunteers(Long[] ids) {
        // 检查所有志愿者是否存在
        for (Long id : ids) {
            if (getById(id) == null) {
                throw new BusinessException(ResultCode.VOLUNTEER_NOT_FOUND);
            }
        }
        return removeByIds(Arrays.asList(ids));
    }

    @Override
    @Transactional
    public boolean updateVolunteerStatus(Long id, Integer status) {
        // 检查志愿者是否存在
        if (getById(id) == null) {
            throw new BusinessException(ResultCode.VOLUNTEER_NOT_FOUND);
        }
        
        // 检查状态值是否合法
        if (status < 0 || status > 2) {
            throw new BusinessException("状态值不合法");
        }

        Volunteer volunteer = new Volunteer();
        volunteer.setId(id);
        volunteer.setStatus(status);
        return updateById(volunteer);
    }

    @Override
    public Volunteer getVolunteerInfo(Long id) {
        Volunteer volunteer = getById(id);
        if (volunteer == null) {
            throw new BusinessException(ResultCode.VOLUNTEER_NOT_FOUND);
        }
        return volunteer;
    }

    // 生成志愿者编号（示例：V + 年月日 + 4位随机数）
    private String generateVolunteerNumber() {
        return "V" + System.currentTimeMillis() + String.format("%04d", (int)(Math.random() * 10000));
    }
} 